package com.jigang.study.netty.handler.messagepack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;

import java.util.List;

/**
 * Message Pack 解码器
 *
 * @author wujigang
 * @date 2019/8/30
 */
public class MsgpackDecoder extends MessageToMessageDecoder<ByteBuf> {
    /**
     * Decode from one message to an other. This method will be called for each written message that can be handled
     * by this encoder.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to
     * @param msg the message to decode to an other one
     * @param out the {@link List} to which decoded messages should be added
     * @throws Exception is thrown if an error accour
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {

        final byte[] array;

        final int len = msg.readableBytes();
        array = new byte[len];

        msg.getBytes(msg.readerIndex(), array, 0, len);

        MessagePack msgpack = new MessagePack();
        out.add(msgpack.read(array));
    }
}
